import { CACHE_ACCOUNT, CACHE_KEEPPWD, CACHE_PASSWORD, CACHE_USERINFO } from "@/global/constants"
import { accountLogin, userRegister } from "@/service/login/login"
import type { IAccount } from "@/types"
import { localCache } from "@/utils/cacheData"
import { defineStore } from "pinia"

interface ILoginState {
  userInfo: any
}

const useLoginStore = defineStore("login", {
  state: (): ILoginState => ({
    userInfo: {}
  }),

  actions: {
    // 账号登录
    async loginAction(account: IAccount, keepPwd: boolean) {
      console.log("store", keepPwd)

      // 1.获取token等信息
      const loginResult = await accountLogin(account)
      console.log("loginStore", loginResult)

      if (loginResult.data.code == 200) {
        const resultData = loginResult.data.data.userInfo
        console.log(resultData)

        resultData && localCache.setCache(CACHE_USERINFO, resultData)
        this.userInfo = resultData

        // 1-2.是否保存账号密码
        if (keepPwd) {
          localCache.setCache(CACHE_KEEPPWD, keepPwd)
          localCache.setCache(CACHE_ACCOUNT, account.account)
          localCache.setCache(CACHE_PASSWORD, account.password)
        } else {
          // 没有勾选记住密码就清空缓存
          localCache.removeCache(CACHE_KEEPPWD)
          localCache.removeCache(CACHE_ACCOUNT)
          localCache.removeCache(CACHE_PASSWORD)
        }
      } else {
        console.log(loginResult.data.message)
        return Promise.reject(loginResult.data.message)
      }
    },

    // 账号注册
    async registerAction(account: IAccount) {
      const registerResult = await userRegister(account)
      console.log(registerResult)

      if (registerResult.data.code == 200) {
        return Promise.resolve(registerResult.data.message)
      } else {
        console.log(registerResult.data.message)
        return Promise.reject(registerResult.data.message)
      }
    },

    // 用户进行刷新的时候默认加载数据的操作
    loadLocalCacheAction() {
      console.log(" ----用户进行刷新的时候默认加载数据的操作")
    }
  }
})

export default useLoginStore
